package com.dailyblue.java.spring.security.security03.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.spring.security.security03.bean.SecurityUsers;
import com.dailyblue.java.spring.security.security03.bean.Users;
import com.dailyblue.java.spring.security.security03.mapper.UsersMapper;
import com.dailyblue.java.spring.security.security03.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("进入到了UsersServiceImpl的loadUserByUsername方法"); // info、debug、warn、error
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("userName", username);
        Users user = usersMapper.selectOne(wrapper);
        if (user == null) {
            log.info("用户名没有找到");
            throw new UsernameNotFoundException("用户名没有找到！");
        }
        request.setAttribute("token", user);
        // 加密密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        // 返回用户信息
        SecurityUsers securityUsers = new SecurityUsers();
        securityUsers.setUser(user);
        log.info("用户信息是：{}", securityUsers);
        return securityUsers;
    }
}
